import { StyleSheet, Text, View, ScrollView, Image, Pressable } from 'react-native';
import React, { useState, useMemo, useCallback } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import ECharts from 'react-native-echarts-pro';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import weekday from 'dayjs/plugin/weekday';
import 'dayjs/locale/zh-cn';
import 'dayjs/locale/en';
import { observer, userStore, deviceStore, appStore } from '~/store';
import { getBloodPressureData } from '~/api/deviceToolsApi';
import { px2dp } from '~/utils/px2dp';
import { width } from '~/utils/px2dp';
import { scale } from '~/utils/px2dp';

interface Props {
    selectIndex: number;
}

dayjs.extend(weekday);
const tabWidth = (width - px2dp(120)) / 3; // 每个 tab 的宽度
export default observer((props: Props) => {
    dayjs.locale(appStore.app.language == 'zh' ? 'zh-cn' : 'en');
    const { selectIndex } = props;
    const navigation: any = useNavigation();
    const { t } = useTranslation();
    const tableData = [
        { id: 1, title: t('BloodData.t1') },
        { id: 2, title: t('BloodData.t2') },
        { id: 3, title: t('BloodData.t3') },
    ];
    const [activeIndex, setActiveIndex] = useState(1);
    const changeTable = (id: number) => {
        setActiveIndex(id);
        const params = buildParams(id, deviceInfo?.device_sn);
        getBloodData(params, id);
    };
    const buildParams = (id: number, device_sn: string, extra?: { date?: dayjs.Dayjs }) => {
        const today = extra?.date ?? currentDate; // 使用传入日期
        switch (id) {
            case 1: // 日
                return { device_sn, type: 'day', day_date: today.format('YYYY/M/D') };
            case 2: // 周
                return {
                    device_sn,
                    type: 'week',
                    week_start: today.startOf('week').format('YYYY/M/D'),
                    week_end: today.endOf('week').format('YYYY/M/D'),
                };
            case 3: // 月
                return { device_sn, type: 'month', month_date: today.format('YYYY/M') };
            default:
                return { device_sn, type: 'day', day_date: today.format('YYYY/M/D') };
        }
    };
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    const { device } = deviceStore;
    const deviceInfo = useMemo(() => {
        let res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        if (deviceStore.device?.connectedDeviceStatus == 1) {
            res = userBindDeviceData.find((item) => item.device_sn == device?.connectDevice?.device_sn);
        } else {
            if (autoConnectDeviceSn) {
                res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
            } else {
                res = userBindDeviceData[0];
            }
        }
        return res;
    }, [
        userBindDeviceData,
        autoConnectDeviceSn,
        deviceStore.device?.connectedDeviceStatus,
        device?.connectDevice?.device_sn,
    ]);
    // 血压echarts
    const [bloodData, setBloodData] = useState({ diastole: 0, heartRate: 0, systolic: 0, time: '' });
    const getBloodData = async (params: any, index: number) => {
        const res = await getBloodPressureData(params);
        const {
            diastole = [],
            heartRate = [],
            heart_rate = [],
            systolic = [],
            time = [],
            week = [],
            days = [],
        } = res.data || {};
        const filterZeros = (arr: number[]) => arr.map((v) => (v && v > 0 ? v : '-'));
        const filterHeartRate: any = (arr: number[]) => arr.map((v) => (v > 0 ? Math.round(v) : '-'));
        if (index === 1) {
            setOption(createOption(time, heartRate));
            setBloodOption(creatBloodOptions(time, filterZeros(systolic), filterZeros(diastole)));
            const lastValidIndex = systolic.findLastIndex((v, i) => v > 0 && diastole[i] > 0);
            if (lastValidIndex !== -1) {
                setBloodData({
                    diastole: diastole[lastValidIndex],
                    heartRate: heartRate[lastValidIndex],
                    systolic: systolic[lastValidIndex],
                    time: time[lastValidIndex],
                });
            }
        } else if (index === 2) {
            const weekLabels = week.map((d) => dayjs(d, 'YYYY/MM/DD').format('ddd'));
            setOption(createOption(weekLabels, filterHeartRate(heart_rate)));
            setBloodOption(creatBloodOptions(weekLabels, filterZeros(systolic), filterZeros(diastole)));
        } else {
            setOption(createOption(days, filterHeartRate(heart_rate)));
            setBloodOption(creatBloodOptions(days, filterZeros(systolic), filterZeros(diastole)));
        }
    };
    const [bloodOption, setBloodOption] = useState({});
    const creatBloodOptions = (time, sbp, dbp) => ({
        title: {
            text: t('BloodData.t4') + '(mmHg)',
            left: 'center',
            top: 10,
            textStyle: {
                color: '#fff',
                fontSize: 16,
            },
        },
        tooltip: {
            trigger: 'axis',
        },
        legend: {
            data: [t('BloodData.t5'), t('BloodData.t6')],
            top: 36,
            textStyle: {
                color: '#fff',
                fontSize: 14,
            },
        },
        grid: {
            left: '0',
            right: '0',
            top: '20%',
            bottom: '2%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            data: time,
            axisLine: {
                lineStyle: {
                    color: '#ccc',
                    type: 'dashed',
                },
            },
            axisTick: { show: false },
            splitLine: { show: false },
        },
        yAxis: {
            type: 'value',
            min: 0, // 固定从 0 开始
            max: 200, // 固定到 200
            axisLine: { show: true },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        series: [
            {
                name: t('BloodData.t5'),
                type: 'line',
                data: sbp,
                smooth: 0.6, // 曲线平滑
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { color: '#FF4D4F', width: 2 },
                itemStyle: { color: '#fff', borderColor: '#FF4D4F', borderWidth: 2 },
            },
            {
                name: t('BloodData.t6'),
                type: 'line',
                data: dbp,
                smooth: 0.6,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { color: '#1890FF', width: 2 },
                itemStyle: { color: '#fff', borderColor: '#1890FF', borderWidth: 2 },
            },
        ],
    });
    const [option, setOption] = useState({});
    const createOption = (xAxisData: string[], yAxisData: number[]) => ({
        title: {
            text: t('BloodData.t7') + '(BPM)',
            top: 10,
            left: 'center',
            textStyle: {
                color: '#fff',
                fontSize: 16,
            },
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
                lineStyle: {
                    type: 'dashed',
                    color: '#ccc',
                },
            },
            backgroundColor: '#584F5E',
            borderRadius: 6,
            padding: 10,
            textStyle: {
                color: '#fff',
            },
            formatter: '{b}<br/>{c} bpm',
            rich: {
                c: {
                    fontSize: 18, // 🔍 放大字体
                    fontWeight: 'bold',
                    color: '#fff',
                    lineHeight: 28,
                },
            },
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
            axisLine: {
                lineStyle: {
                    color: '#ccc',
                    type: 'dashed',
                },
            },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        yAxis: {
            min: 0, // 固定从 0 开始
            max: 200, // 固定到 200
            interval: 50, // 每隔 50 一个刻度
            type: 'value',
            axisLine: { show: true },
            axisTick: { show: false },
            splitLine: {
                show: false,
                lineStyle: {
                    type: 'dashed',
                    color: '#e0e0e0',
                },
            },
        },
        grid: {
            left: '0',
            right: '0',
            top: '18%',
            bottom: '2%',
            containLabel: true,
        },
        series: [
            {
                data: yAxisData,
                smooth: 1,
                type: 'line',
                symbol: 'circle',

                itemStyle: {
                    normal: {
                        color: '#02675f',
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    {
                                        offset: 0,
                                        color: '#01806f', // 0% 处的颜色
                                    },
                                    {
                                        offset: 0.5,
                                        color: '#025f5a', // 50% 处的颜色
                                    },
                                    {
                                        offset: 1,
                                        color: '#04122a', // 100% 处的颜色
                                    },
                                ],
                                global: false, // 缺省为 false
                            },
                        },
                        smooth: true,
                    },
                },
            },
        ],
    });
    // 周、月份切换
    const [currentDate, setCurrentDate] = useState(dayjs());
    // 上一页
    const handlePrev = () => {
        let newDate = currentDate;
        if (activeIndex === 2) newDate = currentDate.subtract(1, 'week');
        else if (activeIndex === 3) newDate = currentDate.subtract(1, 'month');

        const params = buildParams(activeIndex, deviceInfo?.device_sn, { date: newDate });
        getBloodData(params, activeIndex);
        setCurrentDate(newDate);
    };

    const handleNext = () => {
        let newDate = currentDate;
        if (activeIndex === 2) newDate = currentDate.add(1, 'week');
        else if (activeIndex === 3) newDate = currentDate.add(1, 'month');

        const params = buildParams(activeIndex, deviceInfo?.device_sn, { date: newDate });
        getBloodData(params, activeIndex);
        setCurrentDate(newDate);
    };

    // 显示文本
    const weekStart = currentDate.startOf('week');
    const weekEnd = currentDate.endOf('week');
    const displayText =
        activeIndex === 2
            ? `${weekStart.format('MM/DD')}-${weekEnd.format('MM/DD')}`
            : activeIndex === 3
            ? currentDate.format('YYYY-MM')
            : currentDate.format('MM/DD');

    useFocusEffect(
        useCallback(() => {
            if (selectIndex == 3) {
                const params = buildParams(1, deviceInfo?.device_sn); // 默认日数据
                getBloodData(params, 1);
            }
        }, [selectIndex, deviceInfo?.device_sn]),
    );

    return (
        <ScrollView
            contentContainerStyle={styles.contentStyle}
            showsVerticalScrollIndicator={false}
            stickyHeaderIndices={[0]}>
            <View style={[styles.nav]}>
                <View style={[styles.row, styles.between]}>
                    {tableData.map((item: any, index) => {
                        return (
                            <Pressable
                                onPress={() => changeTable(item.id)}
                                key={index}
                                style={[
                                    styles.listTable,
                                    activeIndex === item.id && { backgroundColor: 'rgba(216, 216, 216, 0.32)' },
                                ]}>
                                <Text
                                    style={[
                                        styles.listTableText,
                                        activeIndex === item.id && { fontWeight: 'bold', color: '#000' },
                                    ]}>
                                    {item?.title}
                                </Text>
                            </Pressable>
                        );
                    })}
                </View>
            </View>
            <View style={styles.day}>
                {activeIndex == 1 && (
                    <View style={styles.card}>
                        <View style={[styles.row, styles.between]}>
                            <Text style={styles.title}>
                                {t('BloodData.t8')} {bloodData.time || t('BloodData.t9')}
                            </Text>
                            <Pressable
                                style={styles.row}
                                onPress={() =>
                                    navigation.navigate('DeviceDateView', { deviceInfo, category: 'Bloodcontrast' })
                                }>
                                <Text style={styles.title}>{t('BloodData.t10')}</Text>
                                <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                            </Pressable>
                        </View>
                        <View style={[styles.row, styles.between, { marginTop: px2dp(32) }]}>
                            <View>
                                <Text style={styles.t1}>{bloodData.systolic || '-'}</Text>
                                <Text style={styles.t2}>{t('BloodData.t5')}(mmhg)</Text>
                            </View>
                            <View>
                                <Text style={styles.t1}>{bloodData.diastole || '-'}</Text>
                                <Text style={styles.t2}>{t('BloodData.t6')}(mmhg)</Text>
                            </View>

                            <View>
                                <Text style={styles.t1}>{bloodData.heartRate || '-'}</Text>
                                <Text style={styles.t2}>{t('BloodData.t7')}(bpm)</Text>
                            </View>
                        </View>
                    </View>
                )}
                <View style={[styles.row, styles.between, { marginTop: px2dp(64) }]}>
                    <View style={styles.row}>
                        <Image
                            style={styles.icons}
                            source={{ uri: 'https://line.shbjy.cn//wxdata/imgs/blood/qushi.png' }}
                        />
                        <Text style={styles.title}>{t('BloodData.t11')}</Text>
                    </View>
                    <Pressable
                        style={styles.row}
                        onPress={() => navigation.navigate('DeviceDateView', { deviceInfo, category: 'BloodRecords' })}>
                        <Text style={styles.title}>{t('BloodData.t12')}</Text>
                        <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                    </Pressable>
                </View>

                {(activeIndex == 2 || activeIndex == 3) && (
                    <View style={[styles.row, [{ alignSelf: 'center', marginVertical: px2dp(32) }]]}>
                        <Pressable onPress={handlePrev}>
                            <Icon name={'chevron-back-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                        </Pressable>
                        <Text style={styles.selectDay}> {displayText}</Text>
                        <Pressable onPress={handleNext}>
                            <Icon name={'chevron-forward-outline'} size={px2dp(40)} color={'#fff'}></Icon>
                        </Pressable>
                    </View>
                )}

                <View style={[styles.echarts]}>
                    <ECharts option={option} width={width - px2dp(48)} height={px2dp(600)} />
                </View>
                <Image
                    source={{ uri: 'https://line.shbjy.cn//wxdata/imgs/blood/heart_pic.png' }}
                    resizeMode="contain"
                    style={styles.icons1}
                />
                <View style={[styles.echarts, { marginTop: px2dp(32) }]}>
                    <ECharts option={bloodOption} width={width - px2dp(48)} height={px2dp(600)} />
                </View>
                <Image
                    source={{ uri: 'https://line.shbjy.cn//wxdata/imgs/blood/blood_pic.png' }}
                    resizeMode="contain"
                    style={styles.icons1}
                />
            </View>
            <Pressable
                style={styles.postion_image}
                onPress={() => navigation.navigate('DeviceDateView', { deviceInfo, category: 'BloodHealthweekly' })}>
                <Image style={styles.image} source={{ uri: 'https://line.shbjy.cn//wxdata/imgs/blood/weekly.png' }} />
            </Pressable>
        </ScrollView>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    contentStyle: {
        flexGrow: 1,
        marginHorizontal: px2dp(24),
        paddingBottom: '50%',
    },
    nav: {
        backgroundColor: 'rgba(255, 255, 255, 0.12)',
        flexDirection: 'row',
        alignItems: 'center',
        height: px2dp(80),
        borderRadius: px2dp(99999),
        justifyContent: 'center',
        position: 'relative',
    },
    listTable: {
        height: px2dp(80),
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: px2dp(12),
        borderRadius: px2dp(99999),
        width: tabWidth,
    },
    listTableText: {
        color: '#fff',
        fontSize: scale(28),
    },
    day: {
        flexGrow: 1,
    },
    echarts: {
        height: px2dp(600),

        borderRadius: px2dp(24),
    },
    icons1: {
        marginTop: px2dp(32),
        width: width - px2dp(48),
        height: px2dp(180),
    },
    card: {
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        borderRadius: px2dp(16),
        padding: px2dp(24),
        marginTop: px2dp(32),
    },
    title: {
        color: '#fff',
        fontSize: scale(28),
    },
    t1: {
        color: '#fff',
        fontSize: scale(50),
        fontWeight: 'bold',
        textAlign: 'center',
        marginBottom: px2dp(12),
    },
    t2: {
        color: '#a4a4a4',
        fontSize: scale(24),
        textAlign: 'center',
    },
    icons: {
        width: px2dp(30),
        height: px2dp(30),
        tintColor: '#fff',
        marginRight: px2dp(12),
    },
    selectDay: {
        fontSize: scale(32),
        marginHorizontal: px2dp(24),
        color: '#fff',
        fontWeight: 'bold',
    },
    postion_image: {
        position: 'absolute',
        top: '50%',
        right: px2dp(12),
    },
    image: {
        width: px2dp(120),
        height: px2dp(120),
    },
});
